﻿// <copyright file="VirtualRegistryEntryList.cs" company="Sinclair Community College">
// Copyright 2010 Sinclair Community College
// </copyright>
// <originalAuthor>Patrick S. Seymour (patrick.seymour@gmail.com)</originalAuthor>

namespace SinclairCC.AppV
{
    using System;
    using System.Collections.Generic;

    /// <summary>
    /// This class represents a list of virtual registry entries.
    /// </summary>
    public class VirtualRegistryEntryList
    {
        /// <summary>
        /// The list of virtual registry entries.
        /// </summary>
        private List<VirtualRegistryEntry> entryList;

        /// <summary>
        /// Initializes a new instance of the VirtualRegistryEntryList class.
        /// </summary>
        /// <param name="dataStream">
        /// A memory stream containing the raw virtual registry entry data from the CP file.
        /// </param>
        public VirtualRegistryEntryList(System.IO.MemoryStream dataStream)
        {
            this.entryList = new List<VirtualRegistryEntry>();
            this.ReadSection(dataStream);
        }

        /// <summary>
        /// Gets the list of virtual registry entries.
        /// </summary>
        public List<VirtualRegistryEntry> ObjectList
        {
            get { return this.entryList; }
        }

        /// <summary>
        /// Reads the data for this section from the memory stream.
        /// </summary>
        /// <param name="dataStream">
        /// A memory stream containing the raw virtual registry entry data from the CP file.
        /// </param>
        private void ReadSection(System.IO.MemoryStream dataStream)
        {
            System.IO.BinaryReader streamReader = new System.IO.BinaryReader(dataStream);

            // Read virtual registry entries from the stream until we find one that has a size of zero (0).
            VirtualRegistryEntry lastKey = null;
            VirtualRegistryEntry entry = null;
            do
            {
                if ((entry != null) && (entry.EntryType == RegistryEntryType.Key))
                {
                    lastKey = entry;
                }

                entry = new VirtualRegistryEntry(dataStream);
                if (entry.EntrySize > 0)
                {
                    if ((entry.EntryType == RegistryEntryType.Value) && (lastKey != null))
                    {
                        lastKey.ChildEntries.Add(entry);
                    }
                    else
                    {
                        this.entryList.Add(entry);
                    }
                }
                //// TODO: Should we not add the last entry in the file, the one with the entry size of zero bytes?
            }
            while (entry.EntrySize > 0);

            streamReader.Close();
        }
    }
}
